package com.kzw.oa.system.web;


import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.kzw.core.bean.Msg;
import com.kzw.core.mapper.Jackson;
import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.orm.StringPropertyFilter;
import com.kzw.core.util.BeanUtil;
import com.kzw.core.util.ExtjsUtil;
import com.kzw.core.util.json.JSON;
import com.kzw.core.util.web.ResponseUtils;
import com.kzw.misc.utils.ContextUtil;
import com.kzw.oa.system.bean.TreeNode;
import com.kzw.oa.system.model.AppUser;
import com.kzw.oa.system.model.Department;
import com.kzw.oa.system.model.UserOrg;
import com.kzw.oa.system.service.AppUserService;
import com.kzw.oa.system.service.DepartmentService;
import com.kzw.oa.system.service.UserOrgService;

@Controller
@RequestMapping("/system/dept")
public class DepartmentAction {
	@Autowired
	private DepartmentService deptService;
	@Autowired
	private UserOrgService userOrgService;
	@Autowired
	private AppUserService appUserService;
	
	/**
	  *  组织机构 
	 */
	@RequestMapping("index")	
	public String index() {
		return "system/dept_view";
	}

	/**
	 * 显示列表
	 */
	@RequestMapping("list")
	public void list(HttpServletRequest request, HttpServletResponse response) {

		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		
		String orgSupId = request.getParameter("orgSupId");
		if (StringUtils.isNotEmpty(orgSupId)) {
			Department supOrg = deptService.get(new Long(orgSupId));
			String supOrgPath = (supOrg==null ? "0." : supOrg.getPath());
			filters.add(new StringPropertyFilter("STARTLKS_path", supOrgPath));
		}
		pageRequest.setOrderBy("path");
		pageRequest.setOrderDir("asc");
		
		Page<Department> page = deptService.search2(pageRequest, filters);
		String json = new JSON(page).buildWithFilters(3);
		ResponseUtils.renderJson(response, json);
	}

	/**
	 * 批量删除
	 */
	@RequestMapping("multiDel")
	@ResponseBody
	public Msg multiDel(String[] ids) {
		if (ids != null) {
			for (String id : ids) {
				// 删除某个组织及其下属组织
				Department dept = deptService.get(Long.parseLong(id));
				String hql = "from Department where path like ? order by path desc";
				List<Department> depts = deptService.findByHQL(hql, dept.getPath() + "%");
				for(Department d : depts) {
					deptService.remove(d);
				}
			}
		}
		return new Msg(true);
	}

	/**
	 * 显示详细信息
	 */
	@RequestMapping("get")
	public void get(Long orgId, HttpServletResponse response) {
		Department organization = deptService.get(orgId);
		List<AppUser> list = appUserService.getChargeOrgUsers(organization);
		String chargeIds = "";
		String chargeNames = "";
		if (list != null && list.size() > 0) {
			for (int index = 0; index < list.size(); index++) {
				AppUser au = list.get(index);
				if (index == 0) {
					chargeIds += au.getUserId();
					chargeNames += au.getFullname();
				} else {
					chargeIds += "," + au.getUserId();
					chargeNames += "," + au.getFullname();
				}
			}
		}

		// 将数据转成JSON格式
		Gson gson = new Gson();
		StringBuffer sb = new StringBuffer("{success:true,data:{");
		sb.append("\"orgId\":" + organization.getDepId() + ",");
		sb.append("\"orgName\":" + gson.toJson(organization.getDepName()) + ",");
		if (organization.getOrgDesc() != null) {
			sb.append("\"orgDesc\":" + gson.toJson(organization.getOrgDesc()) + ",");
		}
		sb.append("\"orgSupId\":" + organization.getOrgSupId() + ",");
		sb.append("\"orgType\":" + organization.getOrgType() + ",");
		sb.append("\"code\":\"" + organization.getCode() + "\",");
		sb.append("\"chargeIds\":\"" + chargeIds + "\",");
		sb.append("\"chargeNames\":" + gson.toJson(chargeNames));
		sb.append(",\"sn\":" + (organization.getSn() == null ? 0 : organization.getSn()));
		sb.append("}}");
		
		ResponseUtils.renderJson(response, sb.toString());
	}

	/**
	 * 添加及保存操作
	 */
	@RequestMapping("save")
	@ResponseBody
	public Msg save(Department dept, String chargeIds) {
		if (dept.getDepId() == null) {
			dept.setCreatetime(new Date());
			dept.setUpdatetime(new Date());
			dept.setCreatorId(ContextUtil.getCurrentUserId());
			dept.setUpdateId(ContextUtil.getCurrentUserId());

			deptService.saveOrUpdate(dept);
			
			Long parentId = dept.getOrgSupId();
			if (parentId==null || parentId==0) {
				dept.setPath("0." + dept.getDepId() + ".");
				dept.setDepth(1L);
			} else {
				Department supOrg = deptService.get(parentId);
				dept.setPath(supOrg.getPath() + dept.getDepId() + ".");
				dept.setDepth(supOrg.getDepth() == null ? 1 : supOrg.getDepth() + 1);
			}
			deptService.saveOrUpdate(dept);

			//设置分管领导
			if (StringUtils.isNotBlank(chargeIds)) {
				String[] pids = chargeIds.split(",");
				for (int index = 0; index < pids.length; index++) {
					UserOrg userOrg = new UserOrg();
					userOrg.setUserid(new Long(pids[index]));
					userOrg.setOrgId(dept.getDepId());
					userOrg.setIsPrimary(new Short("0"));
					userOrg.setIsCharge(new Short("1"));
					userOrgService.saveOrUpdate(userOrg);
				}
			}
		} else {
			Department org = deptService.get(dept.getDepId());
			try {
				Long parentId = org.getOrgSupId();
				if (parentId == 0) {
					org.setPath("0." + dept.getDepId() + ".");
					org.setDepth(1l);
				} else {
					Department supOrg = deptService.get(parentId);
					org.setPath(supOrg.getPath() + org.getDepId() + ".");
					org.setDepth(supOrg.getDepth() + 1);
				}
				org.setUpdatetime(new Date());
				org.setUpdateId(ContextUtil.getCurrentUserId());
				BeanUtil.copyNotNullProperties(org, dept);
				deptService.saveOrUpdate(org);

				if (StringUtils.isNotBlank(chargeIds)) {
					//1、获得当前组织的分管领导
					String hql = "from UserOrg where isPrimary=0 and isCharge=1 and dept.depId=?";
					List<UserOrg> list = userOrgService.findByHQL(hql, org.getDepId());
					for(UserOrg uo : list) {
						userOrgService.remove(uo);
					}
					
					// 重新设置分管领导
					String[] pids = chargeIds.split(",");
					for (int index = 0; index < pids.length; index++) {
						UserOrg userOrg = new UserOrg();
						userOrg.setUserid(new Long(pids[index]));
						userOrg.setOrgId(dept.getDepId());
						userOrg.setIsPrimary(new Short("0"));
						userOrg.setIsCharge(new Short("1"));
						userOrgService.saveOrUpdate(userOrg);
					}
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return new Msg(true);
	}

	/**
	 * 取得组织树
	 */
	@RequestMapping("treeAll")
	public void treeAll(HttpServletResponse response) {
		List<TreeNode> nodes = new ArrayList<>(); 
		// 获得根结点
		List<Department> orgList = deptService.getByParent(0L);
		for(Department dept : orgList) {
			TreeNode node = new TreeNode(dept.getDepId(), dept.getDepName(),dept.getPath());
			node.setSpread(true);
			nodes.add(node);
			// 设置子结点
			getChildren(node, dept, null);
		}		
		String json = Jackson.me().toJson(nodes);
		ResponseUtils.renderJson(response, json);
	}
	
	@RequestMapping("tree")
	public void tree(HttpServletResponse response) {
		List<TreeNode> nodes = new ArrayList<>(); 
		// 获得根结点
		Department root = ContextUtil.getCurrentDept();
		// 获得根
		List<Department> orgList = new ArrayList<>();
		orgList.add(root);
		for(Department dept : orgList) {
			TreeNode node = new TreeNode(dept.getDepId(), dept.getDepName(), dept.getPath());
			node.setSpread(true);
			nodes.add(node);
			// 设置子结点
			getChildren(node, dept, null);
		}		
		String json = Jackson.me().toJson(nodes);
		ResponseUtils.renderJson(response, json);
	}
	
	/**
	 * 获得节点的子节点
	 * */
	private void getChildren(TreeNode node, Department dept, String ids) {
		List<Department> orgList = deptService.getByParent(dept.getDepId());
		if(orgList.size() > 0) {
			// 存在子节点
			List<TreeNode> children = new ArrayList<>();
			for(Department d : orgList) {
				TreeNode n = new TreeNode(d.getDepId(), d.getDepName(),d.getPath());
				if(StringUtils.isNotBlank(ids)) {
					if(ids.contains("," + d.getDepId() + ",")) {
						n.setSpread(true);
					}
				}
				children.add(n);
				// 设置子结点
				getChildren(n, d, ids);
			}
			node.setChildren(children);
		}		
	}

	/**
	 * 取得树
	 */
	@RequestMapping("treegrid")
	public void treeGrid(HttpServletResponse response) {
		
		StringBuffer buff = new StringBuffer();
		List<Department> roots = deptService.getByParent(0L);
		for (Department org : roots) {
			//获得对应json
			String json = new JSON(org, true).buildWithFilters(1, "appUsers", "userOrgs");
			buff.append(json).deleteCharAt(buff.length()-1);
			buff.append(getChildList2(org.getDepId()));
		}
		if (!roots.isEmpty()) {
			buff.deleteCharAt(buff.length() - 1);
		}
		ResponseUtils.renderJson(response, buff.toString());
	}
	public String getChildList2(Long parentId) {
		StringBuffer buff = new StringBuffer();
		List<Department> orgList = deptService.getByParent(parentId);
		if (orgList.size() == 0) {
			buff.append(",\"leaf\":true,\"expanded\":true},");
			return buff.toString();
		} else {
			buff.append(",\"expanded\":true,\"children\":[");
			for (Department org : orgList) {
				String json = new JSON(org, true).buildWithFilters(1, "appUsers", "userOrgs");
				buff.append(json).deleteCharAt(buff.length()-1);
				buff.append(getChildList2(org.getDepId()));
			}
			buff.deleteCharAt(buff.length() - 1);
			buff.append("]},");
			return buff.toString();
		}
	}

	/**
	 * 明细
	 */
	@RequestMapping("detail")
	public String detail(String orgId, Model model) {
		if (StringUtils.isNotEmpty(orgId) && !"0".equals(orgId)) {
			Department organization = deptService.get(new Long(orgId));
			// 主要负责人
			String chargeUser = "";
			try {
				Iterator<UserOrg> auit = organization.getUserOrgs().iterator();
				while (auit.hasNext()) {
					UserOrg uo = auit.next();
					if (uo.getIsCharge() != null && uo.getIsCharge() == 1) {
						chargeUser += uo.getAppUser().getFullname() + ",";
					}
				}
			} catch(Exception e) {
				e.printStackTrace();
			}
			
			if (chargeUser.length() > 0) {
				chargeUser = chargeUser.substring(0, chargeUser.length() - 1);
			}
			model.addAttribute("chargeUser", chargeUser);

	
			if (organization.getOrgSupId() != null
					&& organization.getOrgSupId() != -1) {
				Department supOrg = deptService.get(organization
						.getOrgSupId());
				model.addAttribute("supOrg", supOrg);
			}
			model.addAttribute("org", organization);
		}
		return "system/organizationDetail";

	}

	/**
	 * 取得树
	 */
	@RequestMapping("orgStructure")
	public void orgStructure(HttpServletResponse response) {
		
		StringBuffer buff = new StringBuffer("[{id:'" + 0
				+ "',text:'全部',expanded:true,children:[");
		List<Department> orgList = deptService.getByParent(0L);
		for (Department org : orgList) {
			buff.append("{id:'" + org.getDepId()).append(
					"',text:'" + org.getDepName()).append("',")
					.append("flag:'").append("org").append("',");
			buff.append(getDeps(org.getDepId()));
		}
		if (!orgList.isEmpty()) {
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]}]");
		
		ResponseUtils.renderJson(response, buff.toString());
	}

	public String getDeps(Long parentId) {
		StringBuffer buff = new StringBuffer();
		List<Department> orgList = deptService.getByParent(parentId);
		
		Page<AppUser> page = appUserService.getDepUsers(deptService
				.get(parentId).getPath(), null, null);
		List<AppUser> users = page.getData();
		
		if (orgList.size() == 0 && users.size() == 0) {
			buff.append("leaf:true,expanded:true},");
			return buff.toString();
		} else if (orgList.size() == 0 && users.size() != 0) {
			buff.append("expanded:true,children:[");
			buff.append("{id:'org" + parentId
					+ "',text:'员工',flag:'user',expanded:true,children:[");
			buff.append(getUsers(users, parentId));
			buff.deleteCharAt(buff.length() - 1);
			buff.append("]},");
			return buff.toString();
		} else {
			buff.append("expanded:true,children:[");
			for (Department org : orgList) {
				buff.append("{id:'org" + parentId
						+ "',text:'员工',flag:'user',expanded:true,");
				buff.append("children:[");
				buff.append(getUsers(users, parentId));
				buff.append("{id:'" + org.getDepId()).append(
						"',text:'" + org.getDepName()).append("',").append(
						"flag:'").append("org").append("',");
				buff.append(getDeps(org.getDepId()));
			}
			buff.deleteCharAt(buff.length() - 1);
			buff.append("]},");
			return buff.toString();
		}
	}

	/**
	 * 
	 * 根据部门路径取得部门员工<br>
	 * @param 参数 orgPath 组织路径
	 * @return 返回 员工json
	 */
	public String getUsers(List<AppUser> users, Long orgId) {
		StringBuffer buff = new StringBuffer();
		// List<AppUser> users=appUserService.getDepUsers(orgPath, null, null);
		if (users.size() == 0) {
			buff.append("]},");
			return buff.toString();
		} else {
			for (AppUser au : users) {
				buff.append("{id:'" + "org" + orgId + "_" + au.getUserId())
						.append("',text:'" + au.getFullname()).append("',")
						.append("flag:'").append("user").append("',").append(
								"leaf:true,expanded:true").append("},");
			}
			buff.deleteCharAt(buff.length() - 1);
			buff.append("]},");
			return buff.toString();
		}
	}

	/**
	 * 单位的关联下拉
	 */
	@RequestMapping("combo")
	public void combo(HttpServletResponse response) {
		// 只列出本地州下的单位
		List<Department> list;
		AppUser user = ContextUtil.getCurrentUser();
		Department org = deptService.get(user.getDept().getDepId());
		if (!org.getPath().equals("0.1.")) {
			String hql = "from Department where depth=2 and path like ?";
			list = deptService.findByHQL(hql, org.getPath());
		} else {
			String hql = "from Department where depth<3";
			list = deptService.findByHQL(hql);
		}
		
		String json = new JSON(list).buildWithFilters(1);
		ResponseUtils.renderJson(response, json);
	}
	
	/**
	 * iframe页面
	 */
	@RequestMapping("html/add")
	public String addUi(Long parentId, Model model) {
		Department parent = deptService.get(parentId);
		model.addAttribute("parent", parent);
		return "system/dept_form";
	}
	
	@RequestMapping("html/edit")
	public String editUi(Long depId, Model model) {
		Department dept = deptService.get(depId);
		Department parent = deptService.get(dept.getOrgSupId());
		model.addAttribute("dept", dept);
		model.addAttribute("parent", parent);
		return "system/dept_form";
	}

	
	/**
	 * 为authtree组件提供数据
	 * */
	@RequestMapping("orgTree")
	public void orgTree(String ids, HttpServletResponse response) {
		ids = "," + ids + ",";
		List<TreeNode> nodes = new ArrayList<>(); 
		// 获得根结点，或者当前用户可见
		List<Department> orgList = deptService.getByParent(0L);
		for(Department dept : orgList) {
			TreeNode node = new TreeNode(dept.getDepId(), dept.getDepName(),dept.getPath());
			if(ids.contains("," + dept.getDepId() + ",")) {
				node.setSpread(true);
			}
			nodes.add(node);
			// 设置子结点
			getChildren(node, dept, ids);
		}	
		String json = Jackson.me().toJson(nodes);
		// id==>value, children==>list, spread==>checked
		json = json.replace("\"id\"", "\"value\"").replace("\"children\"", "\"list\"");
		json = json.replace("spread", "checked");
		ResponseUtils.renderJson(response, json);
	}
	
	@RequestMapping("html/orgTree")
	public String showTree(String ids, Model model) {
		model.addAttribute("ids", ids);
		return "selector/orgtree";
	}
}
